package com.niit.spark.rdd.test

import org.apache.spark.rdd.RDD
import org.apache.spark.{SparkConf, SparkContext}

/**
 * Date:2025/5/6
 * Author：Ys
 * Description:
 */
object SortByKeyExercise {


  def main(args: Array[String]): Unit = {


    val sparkConf = new SparkConf().setMaster("local[*]").setAppName("SortByKeyExercise")
    val sc = new SparkContext(sparkConf)
    sc.setLogLevel("ERROR")

    val scoresRDD = sc.parallelize(Seq(("Alice", 85), ("Bob", 90), ("Charlie",
      78), ("David", 92), ("Eve", 88)))

    //1. 直接用SortBy
    //val resRDD: RDD[(String, Int)] = scoresRDD.sortBy(_._2, false)


    //2.用sortByKey
    val mapRDD: RDD[(Int, String)] = scoresRDD.map(line => {
      (line._2, line._1) // => (85,"Alice")
    })

    val sortRDD: RDD[(Int, String)] = mapRDD.sortByKey(false)
    //==> (85,"Alice")
    val resRDD: RDD[(String, Int)] = sortRDD.map(line=>{
      (line._2,line._1) //=> ("Alice", 85)
    })

    resRDD.collect().foreach(println)

    sc.stop()

  }

}
